package com.apes.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能：properties文件工具
 *
 * @author xul
 * @create 2017-12-04 9:10
 */
@Component("propertiesUtils")
public class PropertiesUtils {
    private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
    private static final String REGEX = "(\\{\\{)(.+?)(}})";  //{{变量名}}


    @Autowired
    private Environment env;

    public String getProperty(String key) {
        return env.getProperty(key);
    }

    public String replace(String target) {
        return replace(target, v -> {
            String value = getProperty(v);
            if (value == null) {
                throw new RuntimeException(String.format("ESB文件配置错误，参数’%s‘没有在properties文件中配置！", v));
            }
            return value;
        });
    }

    public static String replace(final String source, Function<String, String> func) {
        String field, target = source;
        while (true) {
            field = getVariable(target);
            if (field == null) break;
            target = replace(target, func == null ? field : func.apply(field));
        }
        return target;
    }

    public static boolean exist(String target) {
        String variable = getVariable(target);
        return variable != null;
    }

    public static String getVariable(String target) {
        return getVariable(REGEX, target);
    }

    private static String getVariable(String regex, String target) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(target);
        if (matcher.find()) {
            return matcher.group(2).trim();
        }
        return null;
    }

    public static String replace(String target, String replacement) {
        return replace(REGEX, target, replacement);
    }

    private static String replace(String regex, String target, String replacement) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(target);
        return matcher.replaceFirst(replacement);
    }

}
